package com.zenithsun.news.newscolumns.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.syzg.common.service.impl.BaseServiceImpl;
import com.syzg.common.util.SearchMap;
import com.zenithsun.news.newscolumns.model.NewsColumns;
import com.zenithsun.news.newscolumns.service.NewsColumnsService;
import com.zenithsun.news.newscolumns.dao.NewsColumnsDAO;
import com.zenithsun.common.bean.TreeItem;

@Service("newscolumnsService")
public class NewsColumnsServiceImpl extends BaseServiceImpl<NewsColumns> implements NewsColumnsService {
    
    private NewsColumnsDAO newscolumnsDAO = null;

    @Resource
	public void setnewscolumnsDAO(NewsColumnsDAO newscolumnsDAO) {
		this.setDAO(newscolumnsDAO);
		this.newscolumnsDAO = newscolumnsDAO;
	}

	@Override
	public List<TreeItem> getTreeNewsColumns() throws Exception {
		SearchMap searchMap = SearchMap.forClass(NewsColumns.class);
		searchMap.addOrder("a.orderNo", SearchMap.ORDER_ASC);
		List<NewsColumns> nclist=this.findObjects(searchMap);
		return structureFiliation(nclist);
	}
	
	/**
	 * 构建父子关系
	 * @param nclist
	 */
	private List<TreeItem> structureFiliation(List<NewsColumns> nclist){
		Map<String,TreeItem> ncmap=new HashMap<String,TreeItem>();
		Iterator<NewsColumns> iter=nclist.iterator();
		//现将数据转成TreeItem存储
		while(iter.hasNext()){
			NewsColumns tempNewsColumns=iter.next();
			TreeItem treeItem=new TreeItem(tempNewsColumns.getId(),tempNewsColumns.getName(),tempNewsColumns.getParentId());
			ncmap.put(tempNewsColumns.getId(), treeItem);
		}
		return TreeItem.buildTreeItemList(ncmap);
	}

	@Override
	public List<TreeItem> getFirstFloorNewsColumns() throws Exception {
		SearchMap searchMap = SearchMap.forClass(NewsColumns.class);
		searchMap.addOrder("a.orderNo", SearchMap.ORDER_ASC);
		searchMap.eq("a.parentId", "0");
		List<NewsColumns> nclist=this.findObjects(searchMap);
		Iterator<NewsColumns> iter=nclist.iterator();
		List<TreeItem> listItem=new ArrayList<TreeItem>();
		//现将数据转成TreeItem存储
		while(iter.hasNext()){
			NewsColumns tempNewsColumns=iter.next();
			listItem.add(new TreeItem(tempNewsColumns.getId(),tempNewsColumns.getName(),tempNewsColumns.getParentId()));
		}
		return listItem;
	}
}